কেন কর্মক্ষমতা গুরুত্বপূর্ণ
Node.js .
এই নির্দেশিকাটি বিস্তারিত কর্মক্ষমতা বিশ্লেষণের জন্য অন্তর্নির্মিত সরঞ্জাম এবং জনপ্রিয় তৃতীয় পক্ষের সমাধানগুলিকে কভার করে৷
কর্মক্ষমতা টিপ:
আপগ্রেড করার আগে সর্বদা পরিমাপ করুন।
কর্মক্ষমতা সমস্যাগুলি কোথায় থাকতে পারে তা অনুমান করার পরিবর্তে প্রকৃত বাধাগুলি সনাক্ত করতে এই নির্দেশিকাটির কৌশলগুলি ব্যবহার করুন৷
Node.js পারফরম্যান্স বোঝা
Node.js :
এই সমস্যাগুলি নির্ণয়ের জন্য একটি পদ্ধতিগত পদ্ধতি এবং সঠিক সরঞ্জাম প্রয়োজন।
অন্তর্নির্মিত ডায়গনিস্টিক সরঞ্জাম
console.time() এবং console.timeEnd()
একটি কার্যকলাপ কত সময় নেয় পরিমাপ করার একটি সহজ উপায় হল:
// Measure execution time
console.time('operation');
// Some operation to measure
const array = Array(1000000).fill().map((_, i) => i);
array.sort((a, b) => b - a);
console.timeEnd('operation');
// Output: operation: 123.45ms
প্রক্রিয়া পরিসংখ্যান
Node.js :
// Memory usage
const memoryUsage = process.memoryUsage();
console.log('Memory Usage:');
console.log(` RSS: ${Math.round(memoryUsage.rss / 1024 / 1024)} MB`);
console.log(` Heap Total: ${Math.round(memoryUsage.heapTotal / 1024 / 1024)} MB`);
console.log(` Heap Used: ${Math.round(memoryUsage.heapUsed / 1024 / 1024)} MB`);
console.log(` External: ${Math.round(memoryUsage.external / 1024 / 1024)} MB`);
// CPU usage
const startUsage = process.cpuUsage();
// Simulate CPU work
const now = Date.now();
while (Date.now() - now < 500); // Busy wait for 500ms
const endUsage = process.cpuUsage(startUsage);
console.log('CPU Usage:');
console.log(` User: ${endUsage.user / 1000}ms`);
console.log(` System: ${endUsage.system / 1000}ms`);
// Uptime
console.log(`Process uptime: ${process.uptime().toFixed(2)} seconds`);
Node.js Performance Hooks
Node.js 8.5.0 , perf_hooks :
const { performance, PerformanceObserver } = require('perf_hooks');
// Create a performance observer
const obs = new PerformanceObserver((items) => {
items.getEntries().forEach((entry) => {
console.log(`${entry.name}: ${entry.duration.toFixed(2)}ms`);
});
});
// Subscribe to performance events
obs.observe({ entryTypes: ['measure'] });
// Mark the beginning of an operation
performance.mark('start');
// Simulate some work
const data = [];
for (let i = 0; i < 1000000; i++) {
data.push(i * i);
}
// Mark the end and measure
performance.mark('end');
performance.measure('Data processing time', 'start', 'end');
// Clean up marks
performance.clearMarks();
উন্নত CPU প্রোফাইল
কখন CPU প্রোফাইলার ব্যবহার করবেন
1. সোর্স ম্যাপ সহ V8 প্রোফাইলার
টাইপস্ক্রিপ্ট বা ট্রান্সপিলড জাভাস্ক্রিপ্ট ব্যবহার করা অ্যাপ্লিকেশনগুলির জন্য, অর্থপূর্ণ প্রোফাইলিং ফলাফলের জন্য উত্স মানচিত্র প্রয়োজনীয়:
const v8Profiler = require('v8-profiler-node8');
const fs = require('fs');
const path = require('path');
// Enable source map support for accurate profiling
require('source-map-support').install();
// Start CPU profiling with source map support
v8Profiler.setGenerateType(1); // Include type information
const profile = v8Profiler.startProfiling('CPU profile', true);
// Run code to profile
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Simulate both CPU and I/O work
function processData() {
const start = Date.now();
fibonacci(35);
console.log(`CPU work took: ${Date.now() - start}ms`);
// Simulate async work
setImmediate(() => {
const asyncStart = Date.now();
fibonacci(30);
console.log(`Async work took: ${Date.now() - asyncStart}ms`);
});
}
processData();
// Stop profiling after async work completes
setTimeout(() => {
const profile = v8Profiler.stopProfiling('CPU profile');
profile.export((error, result) => {
const filename = path.join(__dirname, 'profile.cpuprofile');
fs.writeFileSync(filename, result);
console.log(`CPU profile saved to ${filename}`);
profile.delete();
});
}, 1000);
ইনস্টলেশন:
উপরের উদাহরণটি ব্যবহার করতে, আপনাকে v8-প্রোফাইলার প্যাকেজটি ইনস্টল করতে হবে:
npm install v8-profiler-node8
জেনারেট করা .cpuprofile ফাইলটি প্রদর্শনের জন্য Chrome DevTools-এ লোড করা যেতে পারে।
2. Node.js বিল্ট-ইন প্রোফাইল
Node.js :
# Start a Node.js application with profiling enabled
node --prof app.js
# Process the generated log file
node --prof-process isolate-0xNNNNNNNN-NNNN-v8.log > processed.txt
উন্নত মেমরি প্রোফাইল
মেমরি লিক সনাক্তকরণ টিপ:
বিভিন্ন সময়ে নেওয়া একাধিক হিপ স্ন্যাপশট তুলনা করুন এবং প্রত্যাশিতভাবে সংগ্রহ করা আবর্জনা নয় এমন বস্তু সনাক্ত করুন।
Chrome DevTools সহ স্ন্যাপশটগুলি হিপ করুন৷
হিপ স্ন্যাপশটগুলি নির্দিষ্ট সময়ে মেমরির অবস্থা ক্যাপচার করে মেমরি লিক সনাক্ত করতে সহায়তা করে:
const heapdump = require('heapdump');
const fs = require('fs');
const path = require('path');
// Generate some data that might leak
let leakyData = [];
function potentiallyLeaky() {
const data = {
id: Date.now(),
content: Array(1000).fill('potentially leaky data'),
timestamp: new Date().toISOString()
};
leakyData.push(data);
}
// Simulate a memory leak with different retention patterns
setInterval(() => {
potentiallyLeaky();
// Keep only the last 100 items to simulate a partial leak
if (leakyData.length > 100) {
leakyData = leakyData.slice(-100);
}
}, 100);
// Take heap snapshots at intervals
function takeHeapSnapshot(prefix) {
const filename = path.join(__dirname, `${prefix}-${Date.now()}.heapsnapshot`);
heapdump.writeSnapshot(filename, (err, filename) => {
if (err) {
console.error('Failed to take heap snapshot:', err);
} else {
console.log(`Heap snapshot saved to ${filename}`);
}
});
}
// Initial snapshot takeHeapSnapshot('heap-initial');
// Take periodic snapshots
setInterval(() => { takeHeapSnapshot('heap-periodic');
}, 10000);
// Force garbage collection before final snapshot
setTimeout(() => {
if (global.gc) {
global.gc();
console.log('Garbage collection forced');
}
takeHeapSnapshot('heap-final');
}, 30000);
ইনস্টলেশন:
উপরের উদাহরণটি ব্যবহার করতে, আপনাকে হেপডাম্প প্যাকেজটি ইনস্টল করতে হবে:
npm install heapdump
মেমরি লিক শনাক্ত করতে Chrome DevTools-এ হিপ স্ন্যাপশট বিশ্লেষণ করা যেতে পারে।
ইভেন্ট লুপ এবং রিগ্রেশন বিশ্লেষণ
নিরীক্ষণের জন্য ইভেন্ট লুপ মেট্রিক্স
ইভেন্ট লুপ Node.js পারফরম্যান্সের কেন্দ্রবিন্দু। এটিকে ব্লক করা কর্মক্ষমতার অবনতি ঘটায়:
const toobusy = require('toobusy-js');
const http = require('http');
// Configure thresholds (in milliseconds)
toobusy.maxLag(100); // Maximum allowed lag before considering server too busy
toobusy.interval(500); // Check interval for event loop lag
// Create HTTP server with event loop monitoring
const server = http.createServer((req, res) => {
// Check if event loop is overloaded
if (toobusy()) {
res.statusCode = 503; // Service Unavailable
res.setHeader('Retry-After', '10');
return res.end(JSON.stringify({
error: 'Server is too busy',
message: 'Please try again later',
status: 503
}));
}
// Simulate some work based on URL
if (req.url === '/compute') {
// CPU-intensive work
let sum = 0;
for (let i = 0; i < 1e7; i++) {
sum += Math.random();
}
res.end(`Computed: ${sum}`);
} else {
// Normal response
res.end('OK');
}
});
// Add error handling
server.on('error', (err) => {
console.error('Server error:', err);
});
// Start server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// Monitor event loop lag and memory usage
setInterval(() => {
const lag = toobusy.lag();
const mem = process.memoryUsage();
console.log(`Event loop lag: ${lag}ms`);
console.log(`Memory usage: ${Math.round(mem.heapUsed / 1024 / 1024)}MB / ${Math.round(mem.heapTotal / 1024 / 1024)}MB`);
}, 1000);
// Graceful shutdown
process.on('SIGINT', () => {
console.log('Shutting down...');
server.close(() => {
process.exit(0);
});
});
ইনস্টলেশন:
উপরের উদাহরণটি ব্যবহার করতে, আপনাকে tobusy-js প্যাকেজটি ইনস্টল করতে হবে:
npm install toobusy-js
Flame Graphs
শিখা গ্রাফগুলি সিপিইউ স্যাম্পলিং এর একটি ভিজ্যুয়াল উপস্থাপনা প্রদান করে, আপনার অ্যাপ্লিকেশনে কোথায় সময় ব্যয় করা হচ্ছে তা সনাক্ত করতে সহায়তা করে:
# Using 0x for flame graphs (install globally)
npm install -g 0x
# Run your application with 0x
0x app.js
# A browser will open with the flame graph visualization when the process exits
Benchmarking
বেঞ্চমার্কিং সবচেয়ে দক্ষ একটি নির্বাচন করতে বিভিন্ন বাস্তবায়ন তুলনা করতে সাহায্য করে:
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
// Add tests
suite
.add('RegExp#test', function() {
/o/.test('Hello World!');
})
.add('String#indexOf', function() {
'Hello World!'.indexOf('o') > -1;
})
.add('String#includes', function() {
'Hello World!'.includes('o');
})
// Add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// Run benchmarks
.run({ 'async': true });
ইনস্টলেশন:
উপরের উদাহরণটি ব্যবহার করতে, আপনাকে বেঞ্চমার্ক প্যাকেজটি ইনস্টল করতে হবে:
npm install benchmark
Node.js Inspector
Node.js Chrome DevTools debugger profiler :
# Start an application with the inspector
node --inspect app.js
# Start and immediately break (for debugging)
node --inspect-brk app.js
আপনার Node.js অ্যাপ্লিকেশনের জন্য DevTools অ্যাক্সেস করতে Chrome খুলুন এবং chrome://inspect-এ যান। এটি অ্যাক্সেস প্রদান করে:
Clinic.js Suite
Clinic.js Node.js :
# Install the Clinic.js suite
npm install -g clinic
# Use Doctor to identify issues
clinic doctor -- node app.js
# Use Flame to generate CPU flame graphs
clinic flame -- node app.js
# Use Bubbleprof for async operations analysis
clinic bubbleprof -- node app.js
ব্যবহারিক কর্মক্ষমতা নির্ণয়
ধাপ 1: বেসলাইন মেট্রিক্স স্থাপন করুন
আপগ্রেড করার আগে, আপনার অ্যাপ্লিকেশনের জন্য বেসলাইন মেট্রিক্স স্থাপন করুন:
const autocannon = require('autocannon');
const { writeFileSync } = require('fs');
// Run a benchmark against your application
const result = autocannon({
url: 'http://localhost:8080',
connections: 100,
duration: 10
});
// Save the results
result.on('done', (results) => {
console.log('Baseline performance metrics:');
console.log(` Requests/sec: ${results.requests.average}`);
console.log(` Latency: ${results.latency.average}ms`);
writeFileSync('baseline-metrics.json', JSON.stringify(results, null, 2));
});
ধাপ 2: বাধা চিহ্নিত করুন
বাধা সনাক্ত করতে প্রোফাইল ব্যবহার করুন:
ধাপ 3: ঠিক করুন এবং পরীক্ষা করুন
বর্ধিতকরণ প্রয়োগ করার পরে, আপনার বেসলাইনের বিপরীতে বর্ধনগুলি পরীক্ষা করুন।
সাধারণ কর্মক্ষমতা সমস্যা এবং সমাধান
1. মেমরি ফাঁস
উপসর্গ:সময়ের সাথে সাথে মেমরির ব্যবহার বাড়ার সাথে সাথে এটি সমতল নয়।
সমাধান:
2. দীর্ঘ-চলমান অপারেশন
উপসর্গ:উচ্চ ইভেন্ট লুপ ল্যাগ, অসামঞ্জস্যপূর্ণ প্রতিক্রিয়া সময়।
সমাধান:
3. অদক্ষ ডাটাবেস প্রশ্ন
উপসর্গ:ধীর প্রতিক্রিয়া সময়, আরো পিছিয়ে.
সমাধান:
অনুশীলন করুন
সঠিক মডিউল নাম নির্বাচন করুন.
The ______ module in Node.js provides tools for measuring performance.